package com.balabala.gym_system.webSocket;

import com.balabala.gym_system.dao.MessageDao;
import com.balabala.gym_system.pojo.dto.Message;
import com.balabala.gym_system.pojo.dto.UserDto;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Author:zl
 * Date:2023/5/3 11:07
 */
@Slf4j
public class WebSocketHandler extends TextWebSocketHandler {

    //存储客户端的session
    private static  final Map<Long,WebSocketSession> SESSIONS=new ConcurrentHashMap<>();

    //记住上线的人数，TODO 后期把设计成线程安全
    private static  int onlineCount=0;

    //jackson
    private ObjectMapper objectMapper=new ObjectMapper();

    @Autowired
    private MessageDao messageDao;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {

        String username = (String) session.getAttributes().get("username");
        Long uid= (Long) session.getAttributes().get("uid");
        //存储用户的session
        SESSIONS.put(uid,session);
        onlineCount++;
        log.info("用户上线:{},当前在线人数:{}",username,onlineCount);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {

        //{"toId":1,"toUsername":"班长","msg":"您好班长"}
        Long uid= (Long) session.getAttributes().get("uid");
        String username= (String) session.getAttributes().get("username");

        //获取消息
        JsonNode jsonNode = objectMapper.readTree(message.getPayload());
        Long toId=jsonNode.get("toId").asLong();
        String msg=jsonNode.get("msg").asText();
        String toUsername=jsonNode.get("toUsername").asText();

        //发送消息给对应的用户
        log.info("需要给用户:{},发送消息:{}",toUsername,msg);


        //构建消息对象
        Message mongdbMessage = Message.builder().from(UserDto.builder().id(uid).username(username).build())
                .to(UserDto.builder().id(toId).username(toUsername).build())
                .msg(msg).build();

        //将消息保存到mongdb
        mongdbMessage = messageDao.saveMessage(mongdbMessage);


        //查找对应的用户
        WebSocketSession toSession = SESSIONS.get(toId);


        //判断用户是否在线
        if(toSession!=null&&toSession.isOpen()){

            Map map=new HashMap();
            map.put("fromId",uid);
            map.put("msg",msg);
            map.put("fromUsername",username);

            //修改消息为已读状态
            messageDao.updateMessageState(mongdbMessage.getId(),2);

            String sendMessage = objectMapper.writeValueAsString(map);
            toSession.sendMessage(new TextMessage(sendMessage));
        }

    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        log.error("发生异常:{}",exception.getMessage());
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        Long uid= (Long) session.getAttributes().get("uid");
        String username = (String) session.getAttributes().get("username");
        SESSIONS.remove(uid);
        onlineCount--;
        log.info("用户下线:{}，当前在线人数:{}",username,onlineCount);
    }
}
